﻿using IM.Easy.Core.OAuth.Providers;
using IM.Easy.Core.OAuth.ProvidersApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.Core.OAuth
{

    public class OAuthProviderFactory
    {

        private readonly IServiceProvider _serviceProvider;
        private readonly Dictionary<string, Type> _providers = new(StringComparer.OrdinalIgnoreCase);

        public OAuthProviderFactory(IServiceProvider serviceProvider, Dictionary<string, Type> providers)
        {
            _serviceProvider = serviceProvider;
            _providers = providers;
        }



        /// <summary>
        /// 创建指定的提供程序实例。
        /// </summary>
        public AuthProviderAbstract Create(string providerName)
        {
            if (_providers.TryGetValue(providerName, out var providerType))
            {
                //return _serviceProvider.GetRequiredService<GiteeOAuthProvider>();
                return (AuthProviderAbstract)_serviceProvider.GetRequiredService(providerType);
            }

            throw new InvalidOperationException($"未注册提供程序 '{providerName}'。");
        }

        /// <summary>
        /// 创建指定的提供程序实例
        /// </summary>
        /// <param name="providerName"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public AuthProviderAbstract Create(string providerName, AuthOptions options)
        {
            if (_providers.TryGetValue(providerName, out var providerType))
            {
                var provider = (AuthProviderAbstract)Activator.CreateInstance(providerType, options);
                return provider;
            }
            throw new InvalidOperationException($"未注册提供程序 '{providerName}'。");
        }

    }

}
